<?php
/**
 * DummyService.php
 * 文件描述 虚拟对象逻辑页
 * Created on 2020/8/31 18:35
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\xiangji\services;



use app\common\facades\auth\Auth;
use app\common\models\LoveScore;

class LoveScoreService
{
    private $loveScoreModel;

    public function __construct(LoveScore $loveScoreModel)
    {
        $this->loveScoreModel = $loveScoreModel;
    }

    public function getUserLoveScore()
    {
        $user = Auth::guard('api')->user();
        return $user->loveScore->hidden(['id', 'user_id', 'create_time', 'delete_time']);
    }

    public static function updateUserScore(LoveScore $score, int $change, string $scene = '签到奖励')
    {
        LoveScoreLogService::addScoreLog($score,$change, $scene);
        self::changeTotalScore($score, $change);
        return true;
    }

    /**
     * @todo 更新恩爱值账户余额
     * @param LoveScore $score
     * @param int $change
     * @return bool
     */
    public static function changeTotalScore(LoveScore $score, int $change)
    {
        return $score->save(['total_score' => $score->total_score + $change]);
    }

    /**
     * @todo 校验恩爱值账户是否正常
     * @param LoveScore $score
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function checkLoveScoreSafety(LoveScore $score)
    {
        $last_log = $score->logs()->order('id', 'desc')->find();
        if ($score->total_score == 0 && is_null($last_log)) return true;    // 空账户
        return $score->total_score == $last_log->after_score;
    }
}
